package com.example.intermediate_control;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.intermediate_control.util.ViewUtil;

import java.util.Random;

public class LoginAppActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, View.OnFocusChangeListener {


    private Button btnForgetPassword;
    private CheckBox btnRemeberPassword;
    private EditText etInputPassword;
    private TextView tvVerification;
    private EditText etPhone;
    private Button btn_submit;
    private SharedPreferences preferences;
    private RadioButton radioPassword;
    private RadioButton rdbVerification;

    private String mPassword = "111111";
    private String verifyCode;
    private String newPassword;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_app);
        //设置单选按钮监听器
        RadioGroup radioGroup = findViewById(R.id.rdg_login);
        radioGroup.setOnCheckedChangeListener(this);

        //设置单选密码登录按钮
        radioPassword = findViewById(R.id.rdb_passwordLogin);

        //设置单选验证码登录按钮
        rdbVerification = findViewById(R.id.rdb_verificationCodeLogin);

        //输入密码文本,设置焦点变更监听器
        etInputPassword = findViewById(R.id.et_InputPassword);
        etInputPassword.setOnFocusChangeListener(this);
        //遗忘密码按钮,设置点击事件
        btnForgetPassword = findViewById(R.id.btn_forgetPassword);
        btnForgetPassword.setOnClickListener(this);

        //保存数据
        preferences = getSharedPreferences("UserPassword", Context.MODE_PRIVATE);
        //记住密码按钮
        btnRemeberPassword = findViewById(R.id.cb_memoryPassword);

        //验证码
        tvVerification = findViewById(R.id.tv_verification);
        //输入手机号文本
        etPhone = findViewById(R.id.et_InputPhone);
        //设置文本变化监听器,设置手机号和密码的最大长度
        etPhone.addTextChangedListener(new HideTextWatcher(etPhone,11));
        etInputPassword.addTextChangedListener(new HideTextWatcher(etInputPassword,6));
        //拿到登录按钮,设置登录点击触发事件
        btn_submit = findViewById(R.id.btn_Login);
        btn_submit.setOnClickListener(this);
        reload();
    }

    /**
      *
      * @description 密码登录和验证码登录页面修改
      * @param 
      * @return 
      * author snjgm
      * time 2022/7/18 下午2:38
      */
    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int i) {
        switch (i) {
            case R.id.rdb_verificationCodeLogin:
                tvVerification.setText("验证码");
                //1将忘记密码改成获取验证码
                btnForgetPassword.setText("获取验证码");
                //2将提示文字替换
                etInputPassword.setHint("请输入验证码");
                //3将记住密码按钮给隐藏
                btnRemeberPassword.setVisibility(View.GONE);
                break;
            case R.id.rdb_passwordLogin:
                tvVerification.setText("密码");
                btnForgetPassword.setText("忘记密码");
                etInputPassword.setHint("请输入密码");
                btnRemeberPassword.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
      *
      * @description 接收处理后返回的数据
      * @param
      * @return
      * author snjgm
      * time 2022/7/18 下午5:26
      */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if(intent != null && resultCode == Activity.RESULT_OK){
            Bundle bundle = intent.getExtras();
            String newPassword  = bundle.getString("newPassword");
            mPassword = String.format(newPassword);
        }
    }

    /**
      *
      * @description 加载从prefrences中缓存的数据
      * @param 
      * @return 
      * author snjgm
      * time 2022/7/18 下午5:45
      */
    private  void reload(){
        boolean isRemember = preferences.getBoolean("isRemember", false);
        if(isRemember){
            String phone = preferences.getString("phone","");
            etPhone.setText(phone);
            String password = preferences.getString("password","");
            etInputPassword.setText(password);
            Boolean check = preferences.getBoolean("isRemember",false);
            btnRemeberPassword.setChecked(check);
        }
    }

    /**
      *
      * @description 找回密码功能
      * @param 
      * @return 
      * author snjgm
      * time 2022/7/18 上午10:10
      */
    @Override
    public void onClick(View view) {
        String phone = etPhone.getText().toString();
        if (phone.length() < 11) {
            Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            return;
        }
        switch (view.getId()) {
            case R.id.btn_forgetPassword:
                if (radioPassword.isChecked()) {
                    Intent intent = new Intent(this, RetrievedActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("phone", etPhone.getText().toString());
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                } else {
                    //获取验证码,随机生成
                    verifyCode = String.format("%06d", new Random().nextInt(999999));
                    //以下弹出提醒对话框，提示用户记住六位验证码数字
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("请记住验证码");
                    builder.setMessage("手机号" + phone + "的验证码是" + verifyCode);
                    builder.setPositiveButton("好的", null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
                break;

            case R.id.btn_Login:
                //如果是密码登录的方式,判断密码对不对
                if(radioPassword.isChecked()) {
                    if (!mPassword.equals(etInputPassword.getText().toString())) {
                        Toast.makeText(this, "请输入正确的密码", Toast.LENGTH_SHORT).show();
                    } else {
                        if (btnRemeberPassword.isChecked()) {
                            String user = etPhone.getText().toString();
                            String password = etInputPassword.getText().toString();
                            SharedPreferences.Editor edit = preferences.edit();
                            edit.putString("phone", user);
                            edit.putString("password", password);
                            edit.putBoolean("isRemember",btnRemeberPassword.isChecked());
                            edit.commit();
                        }
                    loginSucces();
                }
                }else {
                    if(!verifyCode.equals(etInputPassword.getText().toString())){
                        Toast.makeText(this,"请输入正确的验证码",Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                        loginSucces();
                    }
                }
                break;
        }
    }

    /**
      *
      * @description 成功登录方法
      * @param 
      * @return 
      * author snjgm
      * time 2022/7/18 下午5:55
      */
    private void loginSucces() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("尊敬的"+etPhone.getText().toString()+"用户");
        builder.setMessage("登录成功了");
        builder.setPositiveButton("ok",(dialog,which)->{
            finish();
        });
        builder.setNegativeButton("一会再进去",null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    /**
      *
      *
      * @description 输入手机号码和密码最大长度监听功能
      * @param
      * @return
      * author snjgm
      * time 2022/7/18 上午10:37
      */
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if(view.getId()==R.id.et_InputPassword && hasFocus){
            String phone = etPhone.getText().toString();
            if(phone.length()<11){
                Toast.makeText(this,"请输入11位手机号码",Toast.LENGTH_SHORT).show();
                etPhone.requestFocus();
            }
        }
    }


    /**
      *
      * @description 隐藏键盘功能
      * @param 
      * @return 
      * author snjgm
      * time 2022/7/18 上午10:35
      */
    private class HideTextWatcher implements TextWatcher {
        private EditText et;
        private Integer mMaxlength;
        public HideTextWatcher(EditText etPhone, int maxlength) {
            this.et = etPhone;
            this.mMaxlength = maxlength;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            // 输入文本达到11位(如手机号码),或者达到6位(如登录密码)时关闭输入法
            if ((str.length() == 11 && mMaxlength == 11) || (str.length() == 6 && mMaxlength == 6)) {
                ViewUtil.hideOneInputMethod(LoginAppActivity.this, et);
            }
        }
    }
}
